﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microhard.Notifications.Enum;
using Microhard.Core.DBUtility;
using Microhard.Core;
using Microhard.Notifications.Interfaces;
using System.Threading;
using System.IO;
using Microhard.WeixinMP.Unities;
using Microhard.WeixinMP.Interfaces;
using Microhard.WeixinMP.Models;
using Microhard.Core.Mail;
using System.Configuration;

namespace Microhard.Notifications.Filter
{
    public class NotificationUserFilter : ActionFilterAttribute
    {
        private string _fromMail;
        private string _pwd;
        private string _mailTitle;

        public NotificationUserFilter()
        {
            _fromMail = ConfigurationManager.AppSettings["FromMail"];
            _pwd = ConfigurationManager.AppSettings["PWD"];
            _mailTitle = ConfigurationManager.AppSettings["MailTitle"];
        }
        /// <summary>
        /// 如果一个实体有多个消息模板，则通过此属性确定只使用某一个模板
        /// </summary>
        public string SpecificTemplateCommand { set; get; }
        private Thread sending = null;

        public void SendMsg(object model)
        {
            if (model == null)
                return;
            //创建发送的消息
            try
            {
                var msg = NotificationMsgCreator.CreateMsg(model, this.SpecificTemplateCommand);
                if (msg != null && msg.Count > 0)
                {
                    foreach (var m in msg)
                    {
                        foreach (var u in m.Users)
                        {
                            switch (m.MsgType)
                            {
                                case MsgType.WX:
                                    if (!string.IsNullOrEmpty(m.Content))
                                    {
                                        Log.Debug("NotificationUserFilter.SendMsg", "fakeID:" + u.WXFakeID + " msg:"
                                            + m.Content + " wxmp:" + u.WXMPAccountUserName + " wxmpwd:" + u.WXMPAccountPassword);
                                        WeixinTools.SendTextMessage(u.WXMPAccountUserName, u.WXMPAccountPassword, m.Content, u.WXFakeID);
                                    }
                                    if (m.Images != null)
                                    {
                                        WeixinTools.UploadImage(u.WXMPAccountUserName, u.WXMPAccountPassword, m.Images);
                                        //发送
                                    }
                                    break;
                                case MsgType.Mail:
                                    this.SendMail(u.Mail, m.Content, _mailTitle);
                                    break;
                                case MsgType.SMS: break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("提醒服务发送失败", ex);
            }
            finally
            {
                //销毁子线程
                if (sending != null && sending.IsAlive)
                {
                    sending.Join();
                }
            }
        }

        private void SendMail(string toMail, string message, string title)
        {
            MailTool.SendHTMLMailWithSSL(_fromMail, toMail, title, message, "smtp.qq.com", "465", _fromMail, _pwd);
        }
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            //获得实体
            var rtn = filterContext.HttpContext.Items["executedResult"] as ExecutedResult;
            if (rtn == null || !rtn.IsSucceed || rtn.ExecutedModel == null)
            {
                Log.Error("NotificationUserFilter", "发送实体为空或者执行失败");
            }
            else
            {
                //使用多线程方法，让主线程继续执行
                sending = new Thread(this.SendMsg);
                ////前台线程
                sending.IsBackground = false;
                sending.Start(rtn.ExecutedModel);
            }

        }
    }
}
